﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NetCore;
using NetCore.Attach.BLL;
using NetCore.BLL;
using NetCore.Model;
using NetCore.MVC;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Vue.Web.Controllers
{
    public class AccountController : BaseController
    {
        public IApiService apiService { get; set; }
        public IUserService service { get; set; }
        public IEmailService eService { get; set; }

        [StaticHtml("account/index.html", IsPage = true)]
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Login(UserEntity model, bool rememberMe, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                string strError = "";
                string token = "";
                var result = service.Login(model.UserName, model.Password, ref strError, ref token);
                if (result != null)
                {
                    var claims = new List<Claim>()
                    {
                        new Claim(ClaimTypes.Name,result.UserName) ,
                        new Claim(ClaimTypes.MobilePhone,result.Phone),
                        new Claim(ClaimTypes.Email,result.Email) ,
                         new Claim(ClaimTypes.Authentication,token) ,
                        new Claim(ClaimTypes.NameIdentifier,result.UserId.ToString())

                    };
                    await SignInAsync(claims, result.UserId.ToString(), token, rememberMe);
                    return Json(AjaxResult.Success(new { UserId=result.UserId,UserName = result.UserName, Token = result.Token,MyPermission= result.MyPageEntities }, returnUrl));
                }
               
            }

            // If we got this far, something failed, redisplay form
            return Json(AjaxResult.Error("用户名或者密码不正确！"));
        }

        public IActionResult GetUser()
        {
            var result= this.GetUser<UserEntity>();
            if (result != null)
            {
                return Json(AjaxResult.Success(new { UserId = result.UserId, UserName = result.UserName, Token = result.Token, MyPermission = result.MyPageEntities }));
            }
           
            return Json(AjaxResult.Error("用户尚未登录！"));
        }

        [ResponseCache(CacheProfileName = "default")]
        public FileResult avatar(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                id = this.UserId;
            }
            var bytGraphic = apiService.GetUserAvatar(id);
            return File(bytGraphic, "image/jpeg");
        }
    }
}
